var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const jwt = require("jsonwebtoken");
const unless = require("unless");

// 后端解决跨域导入cors包
const cors = require("cors");
var indexRouter = require("./routes/index");
var userRouter = require("./routes/users");
var coachRouter = require("./routes/coach");
var licenseRouter = require("./routes/license");
let applicationRouter = require("./routes/application");
var carRouter = require("./routes/car");
var classRouter = require("./routes/class");
var practiceRouter = require("./routes/practice");
var examRouter = require("./routes/exam");
var newsRouter = require("./routes/news");
var app = express();

// 导入配置文件
const config = require("./config");

// 解析 token 的中间件
// const expressJWT = require("express-jwt");

// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
// app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/uploads\//,'/api/login'] }))
// app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/uploads\//,'/api/login'] }))
app.all("*", function (req, res, next) {
  
    jwt.verify(req.headers.token || req.query.token, config.jwtSecretKey, function (err, data) {
      if (err &&(req.path !== "/api/login") ) {
        res.send({ code: 0, message: "token无效！" });
      }
    });
   
   next();
 
 
});

app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use("/uploads", express.static(__dirname + "/uploads"));

// 解决跨域
app.use(cors());

app.use("/api", indexRouter);
app.use("/api/user", userRouter);
app.use("/api/coach", coachRouter);
app.use("/api/license", licenseRouter);
app.use("/api/application", applicationRouter);
app.use("/api/car", carRouter);
app.use("/api/class", classRouter);
app.use("/api/practice", practiceRouter);
app.use("/api/exam", examRouter);
app.use("/api/news", newsRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// 错误中间件
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  // 捕获身份认证失败的错误
  if (err.name === "UnauthorizedError")
    return res.send({ message: "认证失败" });
  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
